// pages/invoicing/invoicing.js
const app = getApp()
const cfg = require("../../utils/config.js");
Page({

  /**
   * 页面的初始数据
   */
  data: {
    nvabarData: {
      showCapsule: 1, //是否显示左上角图标  1表示显示  0表示不显示
      title: '开具发票', //导航栏 中间的标题
      white: true, // 是就显示白的，不是就显示黑的。
      address: '' // 加个背景 不加就是没有
    },
    height: app.globalData.height * 2 + 30,
    checkIcon: '../../images/Check3x.png',
    showModalStatus: false,
    tempFileUp: '',
    tempFileDwon: '',
    bankName: '',
    agentBankAccount: '',
    bankCode: '',
    bankNameSubject: '',
    agentBankName: '',
    billTypeName:'',
    billContent:'',
    bankList: [],
    checkTrue: "",
    emailName:'',
    emailTel:'',
    emailAdress:'',
    authorityName: '',
    companyName: '',  // 企业名称
    companyAddr: '', // 企业地址
    companyBankName: '', // 开户银行
    companyBankAccount: '', // 银行账号
    companyNumber: '', // 企业税号
    companyPhone: '', // 企业电话
    identityTips: ''  // 身份证验证提示文字
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    
    this.getBankList();
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.setData({
      bankName: wx.getStorageSync('sellerCompanyName'),
      authorityName: wx.getStorageSync('authorityName')

    })
    // 非登录用户 进入页面带参数 typeId ， typeId=0 个人， typeId=1 企业
    let pages = getCurrentPages();
    let currentPage = pages[pages.length - 1];
    console.log(currentPage.options);
    if (currentPage.options.typeId !== undefined) {
      if (currentPage.options.typeId == "1") {
        this.setData({
          authorityName: "SELLER_USER"
        })
      } else {
        this.setData({
          authorityName: "PERSON_USER"
        })
      }
    } else {
      this.setData({
        authorityName: wx.getStorageSync('authorityName')
      })
    }
    
    //非登录用户填写资料，登录跳转回读取登录前填写信息
    var _exprs = wx.getStorageSync("noLoginInfoSv") || [];
    if (_exprs.length > 1) {
      this.setData({
        bankName: _exprs[1],
        agentBankName: _exprs[2],
        agentBankAccount: _exprs[3],
        billContent: _exprs[4],
        emailName: _exprs[5],
        emailTel: _exprs[6],
        emailAdress: _exprs[7]
      })
      wx.setStorageSync("noLoginInfoSv", '');
      this.setData({
        authorityName: wx.getStorageSync('authorityName')
      })
    }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  changeBankName: function (e) {
    this.setData({
      bankName: e.detail.value
    })
  },
  changeAgentBankName: function (e) {
    this.setData({
      agentBankName: e.detail.value
    })
  },
  changeBankSubject: function (e) {
    console.log(e.detail.value)
    this.setData({
      bankNameSubject: e.detail.value
    })
  },
  changebillContent: function(e){
    this.setData({
      billContent: e.detail.value
    })
  },
  changeBankCode: function (e) {
    console.log(e)
    this.setData({
      agentBankAccount: e.detail.value
    })
  },
  changeEmail: function (e) {
    console.log(e)
    this.setData({
      emailName: e.detail.value
    })
  },
  changeTel: function (e) {
    console.log(e)
    this.setData({
      emailTel: e.detail.value
    })
  },
  changeAdress: function (e) {
    console.log(e)
    this.setData({
      emailAdress: e.detail.value
    })
  },
  getBankList: function () {
    var _this = this;
    wx.request({
      url: cfg.requestURL + '/backend/seller/mobile/billtypelist', //仅为示例，并非真实的接口地址
      data: {
        "token": wx.getStorageSync('token'),
      },
      method: 'GET',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        wx.hideLoading();
        if (res.data.flag) {
          _this.setData({
            bankList: res.data.data,
            bankCode: res.data.data[0].billTypeId,
            billTypeName: res.data.data[0].billTypeName
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            mask: true,
            duration: 1500
          })
        }
      }
    })
  },
  submitBillReq: function () {  // 提交开票申请
    var _this = this;
    var _postURL = '';
    var _postData = {};
    var _inTipsTit = '';
    var _inTipsCode = '';
    let _pages = getCurrentPages();
    let _currentPage = _pages[_pages.length - 1];
    console.log("_currentPage.options = " + _currentPage.options);
    console.log('_this.authorityName--vv',_this.data.authorityName);
    if (_this.data.authorityName == 'PERSON_USER') {
      _postURL = '/backend/person/mobile/billinsert';
      _postData = {
        "sellerId": wx.getStorageSync('personId'),
        "billTypeId": _this.data.bankCode,
        "personName": _this.data.bankName,
        "idCard": _this.data.agentBankName,
        "taxableTotal": _this.data.agentBankAccount,
        "billContent": _this.data.billContent,
        "recivePersonName": _this.data.emailName,
        "mobile": _this.data.emailTel,
        "address": _this.data.emailAdress,
        "companyName": _this.data.companyName,
        "companyAddr": _this.data.companyAddr,
        "companyBank": _this.data.companyBankName,
        "companyBankAccount": _this.data.companyBankAccount,
        "companyNumber": _this.data.companyNumber,
        "companyPhone": _this.data.companyPhone
      };
      _inTipsTit = '请输入姓名';
      _inTipsCode = '请输入身份证';
    }else{
      _postURL = '/backend/seller/mobile/billinsert';
      _postData = {
        "sellerId": wx.getStorageSync('sellerId'),
        "billTypeId": _this.data.bankCode,
        "sellerCompanyName": _this.data.bankName,
        "expressCode": _this.data.agentBankName,
        "taxableTotal": _this.data.agentBankAccount,
        "billContent": _this.data.billContent,
        "recivePersonName": _this.data.emailName,
        "mobile": _this.data.emailTel,
        "address": _this.data.emailAdress
      };
      _inTipsTit = '请输入公司名称';
      _inTipsCode = '请输入信用代码';
    }
    
    if (_this.data.bankName == "") {
      wx.showToast({
        title: _inTipsTit,
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    if (_this.data.agentBankName == "") {
      wx.showToast({
        title: _inTipsCode,
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    if (_this.data.agentBankAccount == "") {
      wx.showToast({
        title: '请输入开票金额',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    if (_this.data.billContent == ""){
      wx.showToast({
        title: '请输入开票内容',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    if (_this.data.emailName == "") {
      wx.showToast({
        title: '请输入收件人',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    if (_this.data.emailTel == "") {
      wx.showToast({
        title: '请输入联系电话',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    if (!(/^1[345789]\d{9}$/.test(_this.data.emailTel))) {
      wx.showToast({
        title: '手机号码填写有误',
        icon: 'none',
        duration: 2000
      })
      return false
    }
    if (_this.data.emailAdress == "") {
      wx.showToast({
        title: '请输入收件人地址',
        icon: 'none',
        duration: 2000
      })
      return false;
    }
    if (wx.getStorageSync('token') == "") {

      // 未登录用户存储信息，
      var _arr = [this.route,
          _this.data.bankName,
          _this.data.agentBankName,
          _this.data.agentBankAccount,
          _this.data.billContent,
          _this.data.emailName,
          _this.data.emailTel,
          _this.data.emailAdress
      ];
      wx.setStorageSync("noLoginInfoSv", _arr);

      wx.showModal({
        title: "温馨提示",
        content: '您还没有登录，将为您跳转到登录页面',
        confirmText: "确定",
        success(res) {
          if (res.confirm) {
            wx.navigateTo({
              url: '../login/login'
            })
          }
        }
      });
      return false;
    }else{
      wx.showLoading({
        title: '加载中...',
      })
    }

    wx.request({
      url: cfg.requestURL + _postURL + '?token=' + wx.getStorageSync('token'), //仅为示例，并非真实的接口地址
      data: _postData,
      method: 'POST',
      header: {
        'content-type': 'application/json' // 默认值
      },
      success(res) {
        wx.hideLoading();
        if (res.data.flag) {
          wx.showToast({
            title: "开票成功",
            icon: 'success',
            mask: true,
            duration: 1500
          })
        } else {
          wx.showToast({
            title: res.data.msg,
            icon: 'none',
            mask: true,
            duration: 1500
          })
        }
      }
    })
  },
  //显示对话框
  showModal: function () {
    // 显示遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
      showModalStatus: true
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export()
      })
    }.bind(this), 200)
  },
  //隐藏对话框
  hideModal: function () {
    // 隐藏遮罩层
    var animation = wx.createAnimation({
      duration: 200,
      timingFunction: "linear",
      delay: 0
    })
    this.animation = animation
    animation.translateY(300).step()
    this.setData({
      animationData: animation.export(),
    })
    setTimeout(function () {
      animation.translateY(0).step()
      this.setData({
        animationData: animation.export(),
        showModalStatus: false
      })
    }.bind(this), 200)
  },
  changeBank: function (event) {
    let postId = event.currentTarget.dataset.id;
    let name = event.currentTarget.dataset.name;
    this.setData({
      bankCode: postId,
      billTypeName: name
    })
    this.hideModal();
  },
  /*身份证验证输入是否正确 
 *身份证号合法性验证 
*支持15位和18位身份证号 *支持地址编码、出生日期、校验位验证*/
  getBirthAndSex: function (e) {  
    var ts = this;  
    var code = this.data.agentBankName //identity 为你输入的身份证  
    console.log(code) 
    var city = { 11: "北京", 12: "天津", 13: "河北", 14: "山西", 15: "内蒙古", 21: "辽宁", 22: "吉林", 23: "黑龙江 ", 31: "上海", 32: "江苏", 33: "浙江", 34: "安徽", 35: "福建", 36: "江西", 37: "山东", 41: "河南", 42: "湖北 ", 43: "湖南", 44: "广东", 45: "广西", 46: "海南", 50: "重庆", 51: "四川", 52: "贵州", 53: "云南", 54: "西藏 ", 61: "陕西", 62: "甘肃", 63: "青海", 64: "宁夏", 65: "新疆", 71: "台湾", 81: "香港", 82: "澳门", 91: "国外 " }; 
    var tip = ""; 
    var pass = true; 
    var reg = /^\d{6}(18|19|20)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)$/; 
    if(!code || !code.match(reg)) { 
      tip = "身份证号格式错误"; 
      pass = false;
    } else if (!city[code.substr(0, 2)]) { 
      tip = "地址编码错误"; pass = false;
    } else { 
      //18位身份证需要验证最后一位校验位 
      if (code.length == 18) {  
        code = code.split('');  
        //∑(ai×Wi)(mod 11)  
        //加权因子  
        var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];  
        //校验位  
        var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];  
        var sum = 0;  
        var ai = 0;  
        var wi = 0;  
        for (var i = 0; i < 17; i++) {   
          ai = code[i];   
          wi = factor[i];   
          sum += ai * wi;  
        }  
        var last = parity[sum % 11];  
        if (last != code[17]) {   
          tip = "校验位错误";   
          pass = false;   
        }  
      } 
    }  
    console.log("pass==="+pass) 
    if (pass) { ts.setData({ allow_id: true }); wx.setStorageSync("idcard", code) } 
    ts.setData({identityTips: tip})
    return pass;
  }
})